﻿/// <reference path="ContractCreat.js" />
var filesHtml = {};
var validate = new Validate();
var url = new Url();
var $userId = url.GetQueryString("userId");
var $orderId = url.GetQueryString("orderId");

var $result_code = url.GetQueryString("result_code");

var $transaction_id = url.GetQueryString("transaction_id");
var $viewpdf_url = url.GetQueryString("viewpdf_url");
var $download_url = url.GetQueryString("download_url");

//有无共同借款人
var $isCoborrow = url.GetQueryString("isUser");

var serializer = new JSONSerializer();
var loanItems;
$(function () {//获取并绑定数据
    $("#verifyOpinion").attr("disabled", "disabled");
    $("li:contains('合同生成')").click();

    $.getJSON("../Handler/LoanProductOrderHandler.ashx",
        {
            Type: 4, OrderId: $orderId, _: Math.random()
        },
        function (result) {
            if (result.Status) {
                updateProgress(result.Data);
                loanItems = result.Data.LoanItems;
                loadVerifyFiles(result.Data.Order.ProductTypeId);
                serializer.DeSerializeToSpan($(".orderInfo"), result.Data.Order);
                serializer.DeSerializeToSpan($(".userInfo"), result.Data.User);
                serializer.DeSerializeToSpan($(".workInfo"), result.Data.Work);
                serializer.DeSerializeToSpan($(".familyInfo"), result.Data.Family);
                serializer.DeSerializeToSpan($("#approvedInfo"), result.Data.Order);
                serializer.DeSerialize($("#contractArea"), result.Data.Order);
                $(".txtContractStartDate").val(result.Data.Order.ContractStartDate);
                $(".txtContractEndDate").val(result.Data.Order.ContractEndDate);
                $(".txtSignDate").val(result.Data.Order.SignDate);

                //---注释掉的内容是合同提交按钮的显示，现在要将合同提交按钮隐藏起来
                //if (result.Data.Order.ContractStartDate != "") {

                //    $(".contract_generate").css("display", "block");
                //    $(".btnContractSubmit").css("display", "block");
                //}


                $("em[data-name='WorkEmail']").text(result.Data.Work.WorkEmail);
                $("em[data-name='IsHaveChildValue']").text(result.Data.Family.IsHaveChildValue);
                $("em[data-name='MaritalStatusValue']").text(result.Data.Family.MaritalStatusValue);
                $("em[data-name='HousePropertyValue']").text(result.Data.Family.HousePropertyValue);
                //单独绑定是否更换产品名称
                $("div.isAccordanceProduct>span").text(result.Data.Order.IsAccordanceProduct ? "是" : "否");
                if (result.Data.Order.IsAccordanceProduct) {
                    $("div.accordanceProduct").css("display", "block")
                        .children("span").text(result.Data.Order.ChangeProductName.split(',')[0]);
                }

                //单独绑定是否联名借款
                $("div.isCoborrowLoan>span").text(result.Data.Order.IsCoborrowLoan ? "是" : "否");
                if (result.Data.Order.IsCoborrowLoan) {
                    $("div.coborrowLoan").css("display", "block");
                    $("div.coborrowLoan>span").text(result.Data.Order.CoborrowName.split(',')[0]);
                    //合同生成页面显示联名借款人证件、住址信息
                    $("#contractArea div.isCoborrow").css("display", "block")

                }
                else {
                    //无联名借款人时去除验证
                    $("div.isCoborrow :text").removeAttr("class", "text");
                }
                if (result.Data.Verify.result) {
                    $.each(result.Data.Verify.result, function (index, item) {
                        if (item.Index == 2) {
                            $("#verifyOpinion").val(item.AuditOpinion);
                        }
                    });
                }

                $.each(result.Data.LoanItems, function (index, item) {
                    if (!filesHtml["content" + item.AuthId]) {
                        filesHtml["content" + item.AuthId] = "";
                    }
                    $("#FileTemplate").tmpl(item.Files).appendTo($("#fileContent"));
                    filesHtml["content" + item.AuthId] += $("#fileContent").html();
                    $("#fileContent").empty();
                });

                // 如果订单是机构签约则出现机构银行卡信息
                if (result.Data.Order.IsAgencyContract == 1) {
                    $("div.orgBankInfo").css("display", "block");
                    $("#OrgBankName").val(result.Data.Organization.BankName);
                    $("#OrgBankBranch").val(result.Data.BankBranch);
                    $("#OrgBankAccount").val(result.Data.Organization.BankAccount);
                }


                //借款订单是否更换产品，根据产品类型分配合约类型
                if (result.Data.Order.ChangeProductName != null) {

                    var str = result.Data.Order.ChangeProductName.split(',');
                    if (str.length == 2) {

                        //如果是分期贷
                        if (str[1] == 31021) {
                            $("#hidContractType").val(30);
                        }
                        else if (str[1] > 31021) {
                            $("#hidContractType").val(31);
                        } else {
                            $("#hidContractType").val(25);
                        }
                    }
                } else {

                    //如果是分期贷
                    if (result.Data.Order.ProductTypeId == 31021) {
                        $("#hidContractType").val(30);
                    }
                    else if (result.Data.Order.ProductTypeId > 31021) {
                        $("#hidContractType").val(31);
                    } else {
                        $("#hidContractType").val(25);
                    }
                }

                //如果不是乐消贷和分期贷则机构选择不可用
                if ($("#hidContractType").val() == "25") {
                    $(".ddlIsAgencyContract").attr("disabled", true);

                    $(".ddlOrganizationId").val("");
                    $(".ddlOrganizationId").attr("disabled", true);
                } else {
                    //签约之前默认为可以机构签约
                    if (result.Data.Order.IsAgencyContract == 0 && result.Data.Order.OrganizationId == 0) {
                        $(".ddlIsAgencyContract").val(1);
                        $(".ddlOrganizationId").val("");
                    } else {
                        $(".ddlIsAgencyContract").val(result.Data.Order.IsAgencyContract);
                        $(".ddlOrganizationId").val(result.Data.Order.OrganizationId);
                    }
                }

                //页面初始时，授权合同的操作
                LoanContractFormation.LoadAuthorization();

            } else {
                alert(result.Message);
            }
            //当选择开始日期后，通过封闭期自动带出封闭结算期或者合同结束期
            $(".txtContractStartDate").change(function () {
                var startDate = $(this).val();
                var monthDiff = parseInt(result.Data.Order.Term);
                if (!isNaN(monthDiff)) {
                    var date = addMonth(startDate, monthDiff);
                    var endDate = subDay(date);
                    $(".dtp_ContractEndDate").val(endDate);
                    $(".txtContractEndDate").val(endDate);
                }
                else {
                    $(this).val("");
                    $(".dtp_ContractStartDate").val("");
                    alert("还没有批核信息！");
                }
            });
        });

    //是否签约机构的选择事件
    $(".ddlIsAgencyContract").change(function () {

        var isAgencyContract = $(".ddlIsAgencyContract").find("option:selected").val();

        if ($("#hidContractType").val() != "25" && (isAgencyContract == 0 || isAgencyContract == "")) {
            alert("此订单的产品类型需选择是否签约及机构！");
            $(".ddlIsAgencyContract").val(1);
        }
    });

    //签约机构的选择事件
    $(".ddlOrganizationId").change(function () {

        var isAgencyContract = $(".ddlIsAgencyContract").find("option:selected").val();
        var orgId = $(".ddlOrganizationId").find("option:selected").val();

        if (isAgencyContract == 1 && orgId != "") {

            $("div.orgBankInfo").css("display", "block");

            //查询机构信息
            $.ajax({
                type: "post",
                url: "../Handler/ContractFormationHandler.ashx",
                dataType: "json",
                data: { type: 39, OrgId: orgId, _: Math.random() },
                async: true,
                cache: true,
                complete: function () {
                },
                success: function (result) {
                    if (result.Status) {
                        $("#OrgBankName").val(result.Data.BankName);
                        $("#OrgBankBranch").val(result.Data.BankBranch);
                        $("#OrgBankAccount").val(result.Data.BankAccount);
                    }
                    else {
                        alert(result.Message);
                    }
                }
            });
        }
        else {
            $("div.orgBankInfo").css("display", "none");
        }
    });


    $("#contractArea .text").change(function () {
        $(this).next("span").text("");
    });


    //页面进度加载隐藏
    $("#Page_loading").css("display", "none");

    //合同菜单层隐藏
    $(".contract_generate").hide();

    //合同授权点击事件
    $(".btnContractAuthorization").bind("click", function () {

        //隐藏合同授权按钮
        $(".btnContractAuthorization").css("display", "none");

        var hidCid = $("#hidCid").val();

        $.ajax({
            type: "post",
            url: "../Handler/ContractFormationHandler.ashx",
            dataType: "json",
            data: { type: 34, OrderId: $orderId, cId: hidCid, _: Math.random() },
            async: true,
            cache: true,
            beforeSend: function () {
                $("#Page_loading").css("display", "block");
            },
            complete: function () {
                $("#Page_loading").css("display", "none");
            },
            success: function (result) {
                if (result.Status) {
                    var model = result.Data;
                    if (model != "") {
                        //window.open(model);
                        location.href = model;
                    }
                } else {
                    alert(result.Message);
                    //显示合同授权 按钮
                    $(".btnContractAuthorization").css("display", "block");
                }
            }
        });
    });

    //开始授权按钮 点击事件
    $(".btnAuthorizationStart").bind("click", function () {

        //保存联名借款人信息及页面上得合同时间信息
        //SaveCoborrowInfoContractInfo();

        var erroNode;
        $("#contractArea .text").each(function () {
            if ($(this).val().trim().length <= 0) {
                erroNode = $(this);
                return false;
            }
        });
        if (erroNode) {
            erroNode.next("span").text(erroNode.attr("data-name") + "不能为空！");
            return;
        }
        //当有联名借款人时验证身份证
        if ($("input[name=CoborrowName]").val() != "") {
            if (validate.CheckIdCard($("input[name=CoborrowIDCard]").val()) != 0) {
                $("input[name=CoborrowIDCard]").next("span").text("无效的身份证号码！");
                return false;
            }
        }

        var $formData = serializer.Serialize($("#contractArea"));
        var startDate = new Date($formData.ContractStartDate);
        var endDate = new Date($formData.ContractEndDate);
        if (startDate > endDate) {
            alert("合同结束日期不能小于合同开始日期！");
            return false;
        }

        //生成还款表信息
        $(".contract_generate").slideDown(100);
        $formData.OrderId = $orderId;
        $formData.Type = "16";
        $formData._ = Math.random();

        $.getJSON("../Handler/LoanProductOrderHandler.ashx", $formData, function (result) {
            if (result.Status) {
                //$(".btnContractSubmit").css("display", "inline");
                alert(result.Message);
            } else {
                alert(result.Message);
            }
        });

        //合同菜单层隐藏
        $(".contract_generate").hide();

        //隐藏合同授权按钮
        $(".btnAuthorizationStart").css("display", "none");

        //查看借款用户是否有CAId，生成电子授权的pdf文件
        LoanContractFormation.IsContractAuthorization();
    });


    //共同借款人合同授权 点击事件
    $(".btnCoborrowAuthorization").bind("click", function () {

        //隐藏合同授权按钮
        $(".btnContractAuthorization").css("display", "none");

        var hidCoid = $("#hidCoid").val();

        $.ajax({
            type: "post",
            url: "../Handler/ContractFormationHandler.ashx",
            dataType: "json",
            data: { type: 34, OrderId: $orderId, cId: hidCoid, _: Math.random() },
            async: true,
            cache: true,
            beforeSend: function () {
                $("#Page_loading").css("display", "block");
            },
            complete: function () {
                $("#Page_loading").css("display", "none");
            },
            success: function (result) {
                if (result.Status) {
                    var model = result.Data;
                    if (model != "") {
                        //window.open(model);
                        location.href = model;
                    }
                } else {
                    alert(result.Message);

                    //显示共同借款人合同授权 按钮
                    $(".btnCoborrowAuthorization").css("display", "block");
                }
            }
        });
    });

    //合同盖章的点击事件
    $(".btnContractSign").bind("click", function () {
        //传入参数为2，4类型的合同，即信用咨询及管理服务协议和还款事项提醒函类型的合同
        var typCode = $("#hidResInfo").val();
        //隐藏合同盖章按钮
        $(".btnContractSign").css("display", "none");

        var perentId = $("#hidContractType").val();

        $.ajax({
            type: "post",
            url: "../Handler/ContractFormationHandler.ashx",
            dataType: "json",
            data: { type: 36, OrderId: $orderId, PerentId: perentId, typCode: typCode, _: Math.random() },
            async: true,
            cache: true,
            beforeSend: function () {
                $("#Page_loading").css("display", "block");
            },
            complete: function () {
                $("#Page_loading").css("display", "none");
            },
            success: function (result) {
                if (result.Status) {
                    var model = result.Data;
                    if (model != null || model.length > 0) {
                        LoanContractFormation.GetDictionaryLoanTypeInfo();

                        //for (var i = 0; i < model.length; i++) {
                        //    $("#ul12_1_" + model[i][0]).empty();

                        //    $("#ul12_1_" + model[i][0]).append("您已经授权成功了！<a href='" + model[i][3] + "' target='_Blank'>点击查看 " + model[i][1] + " 文件</a>");

                        //    $("#ul12_1_" + model[i][0]).removeClass("height");
                        //}


                        //显示合同提交按钮
                        $(".btnContractSubmit").css("display", "block");

                    }
                } else {
                    alert(result.Message);
                    //显示合同盖章 按钮
                    $(".btnContractSign").css("display", "block");
                }
            }
        });
    });

    //$(".contract_generate_a").click(function () {
    //    $(".contract_generate").slideDown(100);
    //})



    //合同生成点击事件
    $(".btnContractCreate").bind("click", function () {
        //隐藏电子授权协议的层
        $("#CFile_Authorization").css("display", "none");
        //隐藏电子授权协议的层
        $("#CoFile_Authorization").css("display", "none");

        //隐藏合同生成按钮
        $(".btnContractCreate").css("display", "none");

        //pdf文件的转换
        LoanContractFormation.GetContractFormationInfo();
    });


    //报表链接
    //$(".btnLoanAgreement").attr("href", "Rep_Loan_LoanAgreement.aspx?OrderId=" + $orderId);
    //$(".btnCreditAgreement").attr("href", "Rep_Loan_CreditAgreement.aspx?OrderId=" + $orderId);
    //$(".btnDebitAuth").attr("href", "Rep_Loan_DebitAuth.aspx?OrderId=" + $orderId);
    //$(".btnRepayReminder").attr("href", "Rep_Loan_RepayReminder.aspx?OrderId=" + $orderId);

    //动态加载讲解人
    $.ajax({
        type: "post",
        url: "../Handler/Operator.ashx",
        dataType: "json",
        data: { type: 15 },
        async: true,
        cache: true,
        complete: function () {
        },
        success: function (result) {
            if (result.Status) {
                var str = '<option value="">请选择</option>';
                $(result.Data).each(function (i, e) {
                    str += '<option value="' + e.OptId + '">' + e.Name + '</option>';
                });
                $(".ddlNarrator").html(str);
            }
            else {
                alert(result.Message);
            }
        }
    });

    //动态机构列表信息
    $.ajax({
        type: "post",
        url: "../Handler/ContractFormationHandler.ashx",
        dataType: "json",
        data: { type: 38 },
        async: true,
        cache: true,
        complete: function () {
        },
        success: function (result) {
            if (result.Status) {
                var str = '<option value="">请选择</option>';
                $(result.Data).each(function (i, e) {
                    str += '<option value="' + e.Id + '">' + e.Name + '</option>';
                });
                $(".ddlOrganizationId").html(str);
            }
            else {
                alert(result.Message);
            }
        }
    });

});


//pdf文件转换，合同类型菜单显示，出借人及借款人加载，保存合同信息的方法
var LoanContractFormation = {
    //动态加载出借人与借款人信息
    SelectLoadAndfinancingInfo: function (typ, perentId) {
        $.ajax({
            type: "post",
            url: "../Handler/ContractFormationHandler.ashx",
            dataType: "json",
            data: { type: 28, OrderId: $orderId, _: Math.random() },
            async: true,
            cache: true,
            complete: function () {
            },
            success: function (result) {
                if (result.Status) {
                    //var s = "夏丽丽-李红,夏丽丽1-李红,夏丽丽2-李红,夏丽丽3-李红,夏丽丽4-李红,夏丽丽5-李红,夏丽丽6-李红";
                    //var ss = s.split(',');

                    var objectStr;  //存储id及出借人和借款人信息
                    var arrList = new Array(); //存数的数组集合

                    var model = result.Data;

                    if (model != null && model.length > 0) {

                        var num = 0;
                        var str = "";

                        if (model.length < 3) {
                            str += "<tr>";
                            for (var i1 = 0; i1 < model.length ; i1++) {
                                str += "<td><a style='cursor: pointer' onclick=\"LoanContractFormation.showHetongInfo('" + model[i1][1] + "','" + model[i1][0] + "'," + typ + "," + perentId + ")\">" + model[i1][2] + "-" + model[i1][4] + "</a></td>";
                                objectStr = [model[i1][1], model[i1][2], model[i1][4]];
                                arrList.push(objectStr);
                            }
                            str += "</tr>";
                        }
                        else if (model.length % 3 == 0) {
                            num = model.length / 3;
                            for (var i = 0; i < num; i++) {
                                str += "<tr>";
                                for (var j = i * 3; j < (i + 1) * 3 ; j++) {
                                    str += "<td><a style='cursor: pointer' onclick=\"LoanContractFormation.showHetongInfo('" + model[j][1] + "','" + model[j][0] + "'," + typ + "," + perentId + ")\">" + model[j][2] + "-" + model[j][4] + "</a></td>";
                                    objectStr = [model[j][1], model[j][2], model[j][4]];
                                    arrList.push(objectStr);
                                }
                                str += "</tr>";
                            }
                        } else {
                            var num1 = (model.length - (model.length % 3)) / 3;
                            num = num1 + 1;

                            for (var i2 = 0; i2 < num; i2++) {

                                if (i2 == num - 1) {
                                    str += "<tr>";
                                    for (var j1 = num1 * 3 ; j1 < model.length ; j1++) {
                                        str += "<td><a style='cursor: pointer' onclick=\"LoanContractFormation.showHetongInfo('" + model[j1][1] + "','" + model[j1][0] + "'," + typ + "," + perentId + ")\">" + model[j1][2] + "-" + model[j1][4] + "</a></td>";

                                        objectStr = [model[j1][1], model[j1][2], model[j1][4]];
                                        arrList.push(objectStr);
                                    }
                                    str += "</tr>";
                                }
                                else {
                                    str += "<tr>";
                                    for (var j2 = i2 * 3; j2 < (i2 + 1) * 3 ; j2++) {
                                        str += "<td><a style='cursor: pointer' onclick=\"LoanContractFormation.showHetongInfo('" + model[j2][1] + "','" + model[j2][0] + "'," + typ + "," + perentId + ")\">" + model[j2][2] + "-" + model[j2][4] + "</a></td>";

                                        objectStr = [model[j2][1], model[j2][2], model[j2][4]];
                                        arrList.push(objectStr);
                                    }
                                    str += "</tr>";
                                }
                            }
                        }
                        if ((typ == 1 && perentId == 25) || typ == 7) {
                            $("#hetong_User1").html(str);
                        }
                    } else {
                        LoanContractFormation.showHetongInfo(0, '', typ, perentId);
                    }
                }
                else {
                    alert(result.Message);
                }
            }
        });
    },
    //pdf文件转换
    GetContractFormationInfo: function () {

        //var listType = new Array();

        //// 获取div层下的所有input文本框，设置为空
        //$(".right_main .contract_generate").find("input:hidden").each(function (index, item) {
        //    listType[index] = $(item).val();
        //});TypeCode: listType, 

        var perentId = $("#hidContractType").val();

        $.ajax({
            type: "post",
            url: "../Handler/ContractFormationHandler.ashx",
            dataType: "json",
            data: { type: 29, OrderId: $orderId, PerentId: perentId, _: Math.random() },
            async: true,
            cache: true,
            beforeSend: function () {
                $("#Page_loading").css("display", "block");
            },
            complete: function () {
                $("#Page_loading").css("display", "none");
            },
            success: function (result) {
                if (result.Status) {
                    var model = result.Data;

                    if (model != null) {

                        //返回更新合同的类型结果，为哪种类型的合同进行盖章
                        $("#hidResInfo").val(model);

                        //显示借款协议层
                        $(".contract_generate").css("display", "block");

                        //合同协议菜单层读取及合同展示
                        LoanContractFormation.GetDictionaryLoanTypeInfo();

                        //显示合同盖章按钮
                        $(".btnContractSign").css("display", "block");

                        $(".btnContractSubmit").css("display", "none");
                    }
                } else {
                    alert(result.Message);
                }
            }
        });
    },
    //合同展示
    showHetongInfo: function (id, creditListId, typ, perentId) {
        $.ajax({
            type: "post",
            url: "../Handler/ContractFormationHandler.ashx",
            dataType: "json",
            data: { type: 30, OrderId: $orderId, financOrderId: id, creditListId: creditListId, typCode: typ, perentId: perentId, _: Math.random() },
            async: true,
            cache: true,
            beforeSend: function () {
                $("#Page_loading").css("display", "block");
            },
            complete: function () {
                $("#Page_loading").css("display", "none");
            },
            success: function (result) {
                if (result.Status) {
                    var model = result.Data;
                    if (model != null) {

                        if (typ == "1" && model.length > 1) {
                            $("#ul12_1_" + typ).append("您已经盖章成功了！");

                            var str = "<table>";
                            var num = 0;

                            if (model.length % 2 == 0) {
                                num = model.length / 2;
                                for (var i = 0; i < num; i++) {
                                    str += "<tr>";
                                    for (var j = i * 2; j < (i + 1) * 2 ; j++) {
                                        str += "<td><a href='" + model[j].ContractPath + "' target='_Blank'>" + model[j].ContractName + " 文件</a></td>";
                                    }
                                    str += "</tr>";
                                }
                            } else {
                                var num1 = (model.length - (model.length % 2)) / 2;
                                num = num1 + 1;

                                for (var i2 = 0; i2 < num; i2++) {
                                    if (i2 == num - 1) {
                                        str += "<tr>";
                                        for (var j1 = num1 * 2 ; j1 < model.length ; j1++) {
                                            str += "<td><a href='" + model[j1].ContractPath + "' target='_Blank'>" + model[j1].ContractName + " 文件</a></td>";
                                        }
                                        str += "</tr>";
                                    }
                                    else {
                                        str += "<tr>";
                                        for (var j2 = i2 * 2; j2 < (i2 + 1) * 2 ; j2++) {
                                            str += "<td><a href='" + model[j2].ContractPath + "' target='_Blank'>" + model[j2].ContractName + " 文件</a></td>";
                                        }
                                        str += "</tr>";
                                    }
                                }
                            }

                            str += "</table>";
                            $("#ul12_1_" + typ).append(str);
                        } else {
                            if (model.length == 0 && (typ == "1" || typ == "7")) {
                                //展示订单的出借人信息
                                LoanContractFormation.SelectLoadAndfinancingInfo(typ, perentId);
                            } else {
                                if (model.length > 0) {
                                    var strUrl = model[0].ContractPath;
                                    var fileName = model[0].ContractName;

                                    $("#ul12_1_" + typ).empty("");

                                    //合同信息展示设置
                                    if (model[0].IsSignature == "1") {
                                        if (typ == "0") {
                                            $("#ul12_1_" + typ).append("您已经授权成功了！<a href='" + strUrl + "' target='_Blank'>点击查看 " + fileName + " 文件</a>");
                                        } else if (typ == "5" || typ == "1") {
                                            $("#ul12_1_" + typ).append("共同借款人已经授权成功了！<a href='" + strUrl + "' target='_Blank'>点击查看 " + fileName + " 文件</a>");
                                        }
                                        else {
                                            $("#ul12_1_" + typ).append("您已经盖章成功了！<a href='" + strUrl + "' target='_Blank'>点击查看 " + fileName + " 文件</a>");
                                        }
                                    } else {
                                        var myPDF = new PDFObject({ url: strUrl }).embed("ul12_1_" + typ);
                                        if (myPDF == false) {
                                            $("#ul12_1_" + typ).append("您的浏览器不支持pdf文件<a href='" + strUrl + "' target='_Blank'>点击下载  " + fileName + "  文件</a>");
                                        } else {
                                            $("#ul12_1_" + typ).css({
                                                "height": "800px"
                                            });
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                else {
                    alert(result.Message);
                }
            }
        });
    },
    //借款类的类别，类别为25，ContractType
    GetDictionaryLoanTypeInfo: function () {

        var perentId = $("#hidContractType").val();

        $.ajax({
            type: "post",
            url: "../Handler/ContractFormationHandler.ashx",
            dataType: "json",
            data: { type: 31, PerentId: perentId, OrderId: $orderId, _: Math.random() },
            async: true,
            cache: true,
            beforeSend: function () {
                $("#Page_loading").css("display", "block");
            },
            complete: function () {
                $("#Page_loading").css("display", "none");
            },
            success: function (result) {
                if (result.Status) {
                    var model = result.Data;
                    if (model != null) {

                        //清空合同层的菜单
                        $(".right_main .contract_generate .ul12").empty();

                        //清空合同层的菜单下的内容层
                        $(".right_main .contract_generate .ul12_1").empty();

                        $.each(model, function (index, item) {

                            //合同层添加菜单信息
                            $("#ContractLoanType").tmpl(item).appendTo(".right_main .contract_generate .ul12");

                            //合同菜单层添加内容
                            $("#ContractLoanInfoli").tmpl(item).appendTo(".right_main .contract_generate .ul12_1");

                            //为借款协议菜单加一个table标签，用作展示出借人及借款人信息列表
                            if ((perentId == 25 && item.DictValue == 1) || item.DictValue == 7) {
                                $("#ul12_1_" + item.DictValue).before("<table id='hetong_User1'></table>");
                            }
                            ////为委托扣款授权书 菜单添加一个table标签，用作展示出借人及借款人信息列表
                            //if (item.DictValue == 3) {
                            //    $("#ul12_1_" + item.DictValue).before("<table id='hetong_User2'></table>");
                            //}
                        });

                        if (model.length > 6) {
                            $(".right_main .contract_generate .ul12_1").css({ "margin-top": "50px" });
                        }

                        //合同类型菜单的第一个li设置默认样式
                        $(".right_main .contract_generate .ul12 li").eq(0).addClass("li1");

                        //合同生成后的合同标签层样式控制
                        $(".right_main .contract_generate .ul12_1>li:not(:first)").hide();
                        $(".right_main .contract_generate .ul12 li").click(function () {
                            $(this).css({ "background": "#FF612C" }).siblings().css({ "background": "#4ABAE0" });
                            $(".right_main .contract_generate .ul12_1>li").eq($(this).index()).show().siblings().hide();

                            //获取点击的合同类型对应下的隐藏域的类型值
                            var code = $(".right_main .contract_generate .ul12 li").eq($(this).index()).children("input").val();
                            //如果是借款协议 或者 委托划扣则隐藏按钮“合同盖章”，否则显示
                            if (code == 1) {
                                $(".btnContractSign").css("display", "none");
                            }
                            else {
                                //如果按钮“合同提交”显示，则隐藏按钮“合同盖章”
                                if ($(".btnContractSubmit").css("display") == "block") {
                                    $(".btnContractSign").css("display", "none");
                                } else {
                                    $(".btnContractSign").css("display", "block");
                                }
                            }
                        });

                        //如果是所有合同都盖完章后，则可以查看所有的合同

                        for (var showI = 0; showI < model.length; showI++) {

                            LoanContractFormation.showHetongInfo(0, '', model[showI].DictValue, perentId);

                            ////菜单借款协议，添加及展示借款人和出借人列表信息
                            //if (model[showI].DictValue == 1) {
                            //    //加载借款人及出借人信息
                            //    LoanContractFormation.SelectLoadAndfinancingInfo(model[showI].DictValue);
                            //} else {
                            //    //其他菜单直接展示合同信息
                            //    //合同展示
                            //    LoanContractFormation.showHetongInfo(0, '', model[showI].DictValue);
                            //}
                        }
                    }
                }
                else {
                    alert(result.Message);
                }
            }
        });
    },
    //查看借款用户是否有CA，是否有授权，并且生成授权协议
    IsContractAuthorization: function () {

        var perentId = $("#hidContractType").val();

        $.ajax({
            type: "post",
            url: "../Handler/ContractFormationHandler.ashx",
            dataType: "json",
            data: { type: 32, OrderId: $orderId, PerentId: perentId, isUser: 0, _: Math.random() },
            async: true,
            cache: true,
            beforeSend: function () {
                $("#Page_loading").css("display", "block");
            },
            complete: function () {
                $("#Page_loading").css("display", "none");
            },
            success: function (result) {
                if (result.Status) {
                    var model = result.Data;
                    if (model != null) {
                        $("#hidCid").val(model.ID);
                        var strUrl = model.ContractPath;

                        var myPDF = new PDFObject({ url: strUrl }).embed("CFile_Authorization");
                        if (myPDF == false) {
                            $("#CFile_Authorization").append("您的浏览器不支持pdf文件<a href='" + strUrl + "' target='_Blank'>点击下载 " + model.ContractName + " 文件</a>");

                        } else {
                            $("#CFile_Authorization").css({
                                "height": "800px"
                            });
                        }

                        //借款人  合同授权按钮显示
                        $(".btnContractAuthorization").css("display", "block");
                    } else {
                        alert("用户授权不成功，身份信息或许有误！");
                    }
                } else {
                    alert(result.Message);
                }
            }
        });
    },
    //查看共同借款人用户是否有授权，并生成授权协议
    IsCoborrowAuthorization: function () {

        var perentId = $("#hidContractType").val();

        $.ajax({
            type: "post",
            url: "../Handler/ContractFormationHandler.ashx",
            dataType: "json",
            data: { type: 32, OrderId: $orderId, PerentId: perentId, isUser: 1, _: Math.random() },
            async: true,
            cache: true,
            beforeSend: function () {
                $("#Page_loading").css("display", "block");
            },
            complete: function () {
                $("#Page_loading").css("display", "none");
            },
            success: function (result) {
                if (result.Status) {
                    var model = result.Data;
                    if (model != null) {
                        //显示共同借款人的层
                        $("#CoFile_Authorization").css("display", "block");

                        $("#hidCoid").val(model.ID);
                        var strUrl = model.ContractPath;

                        var myPDF = new PDFObject({ url: strUrl }).embed("CoFile_Authorization");
                        if (myPDF == false) {
                            $("#CoFile_Authorization").append("您的浏览器不支持pdf文件<a href='" + strUrl + "' target='_Blank'>点击下载 " + model.ContractName + " 文件</a>");

                        } else {
                            $("#CoFile_Authorization").css({
                                "height": "800px"
                            });
                        }

                        //共同借款人  合同授权按钮显示
                        $(".btnCoborrowAuthorization").css("display", "block");
                    }
                        //如果共同借款人不存在则继续下一步的合同生成
                    else {
                        //显示合同生成按钮
                        $(".btnContractCreate").css("display", "block");
                    }
                } else {
                    alert(result.Message);
                }
            }
        });
    },

    //手动签章成功后，页面返回后查看签章的电子授权
    LoadAuthorization: function () {

        //手动签章成功后的操作，修改合同文件是否授权及保存路径
        if ($result_code == "3000") {

            //合同授权按钮 隐藏
            $(".btnContractAuthorization").css("display", "none");

            $.ajax({
                type: "post",
                url: "../Handler/ContractFormationHandler.ashx",
                dataType: "json",
                data: { type: 33, OrderId: $orderId, transactionId: $transaction_id, viewpdfURL: $viewpdf_url, _: Math.random() },
                async: true,
                cache: true,
                beforeSend: function () {
                    $("#Page_loading").css("display", "block");
                },
                complete: function () {
                    $("#Page_loading").css("display", "none");
                },
                success: function (result) {
                    if (result.Status) {
                        var model = result.Count;
                        if (model > 0) {

                            location.href = "/View/ContractCreat.aspx?orderId=" + $orderId;
                        }
                    } else {
                        alert(result.Message);
                    }
                }
            });
        }
            //else if ($isCoborrow == "1") {
            //    //查看共同借款人用户是否有授权
            //    LoanContractFormation.IsCoborrowAuthorization();
            //}
        else {
            //页面初始化时查看授权合同文件
            LoanContractFormation.SelectContractInfo();
        }
    },
    // 查询合同信息，即电子授权合同信息
    SelectContractInfo: function () {

        var perentId = $("#hidContractType").val();

        $.ajax({
            type: "post",
            url: "../Handler/ContractFormationHandler.ashx",
            dataType: "json",
            data: { type: 35, OrderId: $orderId, PerentId: perentId, _: Math.random() },
            async: true,
            cache: true,
            beforeSend: function () {
                $("#Page_loading").css("display", "block");
            },
            complete: function () {
                $("#Page_loading").css("display", "none");
            },
            success: function (result) {
                if (result.Status) {
                    var model = result.Data;
                    if (model != null) {
                        //如果查询的签完章的合同只有一条，并且是电子授权的合同，否则循环签完所有的合同信息
                        if (model.length == 1) {
                            if (model[0].TypeCode == 0) {
                                $("#hidCid").val(model[0].ID);
                                var strUrl = model[0].ContractPath;
                                //如果已经盖章了
                                if (model[0].IsSignature == 1) {

                                    //隐藏合同授权按钮
                                    $(".btnContractAuthorization").css("display", "none");

                                    $("#CFile_Authorization").append("您已经授权成功了！<a href='" + strUrl + "' target='_Blank'>点击查看 " + model[0].ContractName + " 文件</a>");

                                    //共同借款人是否有CAId，生成电子授权的pdf文件
                                    LoanContractFormation.IsCoborrowAuthorization();

                                }
                            }
                        } //如果是两条，借款人和共同借款人的信息
                        else if (model.length == 2) {

                            $("#CoFile_Authorization").css("display", "block");

                            for (var i = 0; i < model.length; i++) {
                                //借款人
                                if (model[i].TypeCode == 0) {
                                    $("#hidCid").val(model[i].ID);
                                    var strUrl = model[i].ContractPath;
                                    //如果已经盖章了
                                    if (model[i].IsSignature == 1) {
                                        $("#CFile_Authorization").append("您已经授权成功了！<a href='" + strUrl + "' target='_Blank'>点击查看 " + model[i].ContractName + " 文件</a>");
                                    }
                                }
                                //共同借款人
                                if ((model[i].TypeCode == 5 && perentId == 25) || (model[i].TypeCode == 1) && perentId != 25) {
                                    $("#hidCoid").val(model[i].ID);
                                    var strUrl = model[i].ContractPath;
                                    //如果已经盖章了
                                    if (model[i].IsSignature == 1) {
                                        $("#CoFile_Authorization").append("共同借款人已经授权成功了！<a href='" + strUrl + "' target='_Blank'>点击查看 " + model[i].ContractName + " 文件</a>");
                                    }
                                }
                            }
                            //显示合同生成按钮
                            $(".btnContractCreate").css("display", "block");
                            //隐藏合同授权按钮
                            $(".btnContractAuthorization").css("display", "none");
                            //隐藏共同借款人合同授权按钮
                            $(".btnCoborrowAuthorization").css("display", "none");

                        }
                        else {
                            //显示借款协议层
                            $(".contract_generate").css("display", "block");
                            LoanContractFormation.GetDictionaryLoanTypeInfo();
                            //显示合同提交按钮
                            $(".btnContractSubmit").css("display", "block");
                        }
                    }
                    //如果电子授权文件不存在或者没有盖章，则需要生成文件
                    if (model == null || model.IsSignature == 0) {
                        //查看用户是否有CAId，生成电子授权的pdf文件
                        //LoanContractFormation.IsContractAuthorization();

                        //开始授权按钮 显示
                        $(".btnAuthorizationStart").css("display", "block");
                    }
                } else {
                    alert(result.Message);
                }
            }
        });
    }
}


//客服人员向结算中心提交合同
$(".btnContractSubmit").bind("click", function () {
    $.ajax({
        type: "get",
        url: "../Handler/LoanProductOrderHandler.ashx",
        dataType: "json",
        data: { OrderId: $orderId, Type: 19, _: Math.random() },
        success: function (result) {
            alert(result.Message);
            if (result.Status) {
                location.href = "/View/LoanOrderList.aspx?css=1017";
            }
        }
    });
});


//保存合同信息，将合同信息添加到数据库中保存



/*
 * date:当前日期,格式:yyyy/MM/dd(如:2011/09/26 2011/9/9)
 * months:要添加的月数
 * return:返回结果,格式:yyyy/MM/dd
 */
function addMonth(sDate, num) {

    var aYmd = sDate.split('/');
    var dt = new Date(aYmd[0], aYmd[1] - 1, aYmd[2]);
    dt.setMonth(dt.getMonth() + num);
    var y = dt.getFullYear();
    var m = dt.getMonth();
    var d = dt.getDate();
    //月份是从0开始啊！！！！
    m++;
    //if (m == 0) { m = 12; y = y - 1; }
    if (m < 10) m = '0' + m;
    if (d < 10) d = '0' + d;
    return y + '/' + m + '/' + d;
}
function subDay(sDate) {
    var dt = new Date(sDate);
    dt.setDate(dt.getDate() - 1);
    var y = dt.getFullYear();
    var m = dt.getMonth();
    var d = dt.getDate();
    //月份是从0开始啊！！！！
    m++;
    if (m < 10) m = '0' + m;
    if (d < 10) d = '0' + d;
    return y + '/' + m + '/' + d;
}



//更新进度条
function updateProgress(data) {
    var total = 0, count = 5;
    if (data.Order) {
        total += 100 / count;
    }
    if (data.Family) {
        total += 100 / count;
    }
    if (data.User) {
        total += 100 / count;
    }
    if (data.Work) {
        total += 100 / count;
    }
    if (data.LoanItems && data.LoanItems.length > 0) {
        total += 100 / count;
    }
    total = parseInt(total);
    $(".progressBar").text(total + "%").css("width", total + "%");
}
//加载审核文件项目
function loadVerifyFiles(productId) {
    $.getJSON("../Handler/ProductHandler.ashx",
        { Id: productId, Type: 5, _: Math.random() },
        function (result) {
            if (result.Status) {
                $("#verifyList").empty();
                $.each(result.Data, function (index, item) {
                    $("#AuthentionTemplate").tmpl(item).appendTo("#verifyList").find(".openLayout").click(function () {
                        var authId = $(this).attr("data-authid");
                        $("#authId").val(authId);
                        $("#filelist").empty();
                        $("#filelist").html(filesHtml["content" + authId]);
                        loadZoomScript();
                    });
                });
                updateItemsStatus();
            } else {
                alert(result.Message);
            }
        });
}
//更新认证信息
function updateItemsStatus() {
    $.each(loanItems, function (index, item) {
        var dom = $("#verifyList div[data-authid='" + item.AuthId + "']");
        if (dom) {
            dom.attr("data-uploaded", true);
            if (item.Passed) {
                dom.find(".verifyStatus").text("已通过审核");
            }
            if (item.Files.length > 0) {
                dom.find(".uploadStatus").text("资料已上传");
                dom.find(".openLayout").show();
            }
        }
    });
    $("#verifyList").children("div:not('[data-uploaded]')").remove();
}
//添加预览脚本
function loadZoomScript() {
    $("#zoomScript").remove();
    $("#zoom").remove();
    var myScript = document.createElement("script");
    myScript.type = "text/javascript";
    myScript.id = "zoomScript";
    myScript.src = "../Plugins/gurdeZoom/js/zoom.min.js";
    document.body.appendChild(myScript);
}